<?php

namespace app\index\controller;

use addons\wechat\model\WechatCaptcha;
use app\admin\library\Auth;
use app\common\controller\Frontend;
use app\common\library\Ems;
use app\common\library\Sms;
use think\Config;
use think\Cookie;
use think\Hook;
use think\Session;
use think\Validate;

/**
 * 会员中心
 */
class User extends Frontend
{
    protected $layout = 'default';
    protected $noNeedLogin = ['login', 'register', 'third', 'admin'];
    protected $noNeedRight = ['*'];

    public function _initialize()
    {
        parent::_initialize();
        $auth = $this->auth;

        if (!Config::get('fastadmin.usercenter')) {
            $this->error(__('User center already closed'));
        }

        //监听注册登录注销的事件
        Hook::add('user_login_successed', function ($user) use ($auth) {
            $expire = input('post.keeplogin') ? 30 * 86400 : 0;
            Cookie::set('uid', $user->id, $expire);
            Cookie::set('token', $auth->getToken(), $expire);
        });
        Hook::add('user_register_successed', function ($user) use ($auth) {
            Cookie::set('uid', $user->id);
            Cookie::set('token', $auth->getToken());
        });
        Hook::add('user_delete_successed', function ($user) use ($auth) {
            Cookie::delete('uid');
            Cookie::delete('token');
        });
        Hook::add('user_logout_successed', function ($user) use ($auth) {
            Cookie::delete('uid');
            Cookie::delete('token');
        });
    }

    /**
     * 空的请求
     * @param $name
     * @return mixed
     */
    public function _empty($name)
    {
        $data = Hook::listen("user_request_empty", $name);
        foreach ($data as $index => $datum) {
            $this->view->assign($datum);
        }
        return $this->view->fetch('user/' . $name);
    }

    /**
     * 会员中心
     */
    public function index()
    {
        $this->view->assign('title', __('User center'));
        $calss_user = db('school_calss_user')->alias('b')
            ->field('a.*,b.use_class_hour,b.total_class_hour,c.nickname')
            ->join('school_class a', 'a.id = b.class_id', 'left')
            ->join('ed_admin c', 'c.id = a.admin_id', 'left')
            ->where('b.status', '0')
            ->where('user_id', $this->auth->id)->select();
        $school_class_name = [];
        foreach ($calss_user as $k => $v) {
            if ($k == 0) {
                $school_class_name[] = $v['class_name'] . '(' . $v['nickname'] . ')<br>已消费' . $v['use_class_hour'] . ' 总课时' . $v['total_class_hour'];
            } else {
                $school_class_name[] = '<br />' . $v['class_name'] . '(' . $v['nickname'] . ')已消费' . $v['use_class_hour'] . ' / 总课时' . $v['total_class_hour'];
            }
        }
        $ksjcount = db('school_coupon')->where('user_id', $this->auth->id)->where('status', '0')->count();

        $this->assign('ksjcount', $ksjcount);
        if (!$school_class_name) {
            $school_class_name = ['暂无班级'];
        }
        $this->assign('school_class_name', $school_class_name);
        return $this->view->fetch();
    }

    /**
     * 注册会员
     */
    public function register()
    {
        $url = $this->request->request('url', '');
        if ($this->auth->id) {
            $this->success(__('You\'ve logged in, do not login again'), $url ? $url : url('user/index'));
        }
        if ($this->request->isPost()) {
            $username = $this->request->post('username');
            $password = $this->request->post('password');
            $email = $this->request->post('email');
            $mobile = $this->request->post('mobile', '');
            $captcha = $this->request->post('captcha');
            $token = $this->request->post('__token__');
            $rule = [
                'username' => 'require|length:3,30',
                'password' => 'require|length:6,30',
                'email' => 'require|email',
                'mobile' => 'regex:/^1\d{10}$/',
                '__token__' => 'require|token',
            ];

            $msg = [
                'username.require' => 'Username can not be empty',
                'username.length' => 'Username must be 3 to 30 characters',
                'password.require' => 'Password can not be empty',
                'password.length' => 'Password must be 6 to 30 characters',
                'email' => 'Email is incorrect',
                'mobile' => 'Mobile is incorrect',
            ];
            $data = [
                'username' => $username,
                'password' => $password,
                'email' => $email,
                'mobile' => $mobile,
                '__token__' => $token,
            ];
            //验证码
            $captchaResult = true;
            $captchaType = config("fastadmin.user_register_captcha");
            if ($captchaType) {
                if ($captchaType == 'mobile') {
                    $captchaResult = Sms::check($mobile, $captcha, 'register');
                } elseif ($captchaType == 'email') {
                    $captchaResult = Ems::check($email, $captcha, 'register');
                } elseif ($captchaType == 'wechat') {
                    $captchaResult = WechatCaptcha::check($captcha, 'register');
                } elseif ($captchaType == 'text') {
                    $captchaResult = \think\Validate::is($captcha, 'captcha');
                }
            }
            if (!$captchaResult) {
                $this->error(__('Captcha is incorrect'));
            }
            $validate = new Validate($rule, $msg);
            $result = $validate->check($data);
            if (!$result) {
                $this->error(__($validate->getError()), null, ['token' => $this->request->token()]);
            }
            if ($this->auth->register($username, $password, $email, $mobile)) {
                $this->success(__('Sign up successful'), $url ? $url : url('user/index'));
            } else {
                $this->error($this->auth->getError(), null, ['token' => $this->request->token()]);
            }
        }
        //判断来源
        $referer = $this->request->server('HTTP_REFERER');
        if (!$url && (strtolower(parse_url($referer, PHP_URL_HOST)) == strtolower($this->request->host()))
            && !preg_match("/(user\/login|user\/register|user\/logout)/i", $referer)) {
            $url = $referer;
        }
        $this->view->assign('captchaType', config('fastadmin.user_register_captcha'));
        $this->view->assign('url', $url);
        $this->view->assign('title', __('Register'));
        return $this->view->fetch();
    }

    public function admin()
    {
        $nickname = $this->request->post('nickname');
        $mobile = $this->request->post('mobile');
        if (!$nickname || !$mobile) {
            $this->error('参数不能为空');
        }
        $userinfo = Session::get("wechat-userinfo");
        $admin_info = db('admin')->where('username', $nickname)->find();
        if (!$admin_info) {
            $this->error('用户不存在');
        }
        $third_info = db('third')->where('admin_id', $admin_info['id'])->find();
        if ($third_info) {
            $this->error('该用户以绑定过了');
        }
        $admin_auth = new Auth();
        $admin_status = $admin_auth->login($nickname, $mobile);
        if ($admin_status) {
            $values = [
                'platform' => 'wechat',
                'user_id' => 0,
                'admin_id' => $admin_info['id'],
                'openid' => $userinfo['openid'],
                'openname' => isset($userinfo['userinfo']['nickname']) ? $userinfo['userinfo']['nickname'] : '',
                'access_token' => $userinfo['access_token'],
                'refresh_token' => $userinfo['refresh_token'],
                'expires_in' => $userinfo['expires_in'],
                'logintime' => time(),
                'expiretime' => time() + $userinfo['expires_in'],
            ];
            $third = \addons\third\model\Third::create($values);
            $this->success("账号绑定成功", '/701.php');
        } else {
            $this->error('密码错误');
        }
    }

    /**
     * 会员登录
     */
    public function login()
    {
        $url = $this->request->request('url', '');
        if ($this->auth->id) {
            $this->success(__('You\'ve logged in, do not login again'), $url ? $url : url('user/index'));
        }
        if ($this->request->isPost()) {
            // $account = $this->request->post('account');
            // $password = $this->request->post('password');
            $nickname = $this->request->post('nickname');
            $mobile = $this->request->post('mobile');
            $keeplogin = (int)$this->request->post('keeplogin');
            $token = $this->request->post('__token__');
            $rule = [
                // 'account'   => 'require|length:3,50',
                // 'password'  => 'require|length:6,30',
                '__token__' => 'require|token',
            ];

            $msg = [
                // 'account.require'  => 'Account can not be empty',
                // 'account.length'   => 'Account must be 3 to 50 characters',
                //'password.require' => 'Password can not be empty',
                //'password.length'  => 'Password must be 6 to 30 characters',
            ];
            $data = [
                // 'account'   => $account,
                // 'password'  => $password,
                '__token__' => $token,
            ];
            $validate = new Validate($rule, $msg);
            $result = $validate->check($data);
            $admin_info = db('admin')->where('nickname', $nickname)->where('mobile', $mobile)->find();
            if ($admin_info) {
                $third_info = db('third')->where('admin_id', $admin_info['id'])->find();
                if ($third_info) {
                    $this->error('该老师以绑定过了');
                }
                $userinfo = Session::get("wechat-userinfo");
                $values = [
                    'platform' => 'wechat',
                    'user_id' => 0,
                    'admin_id' => $admin_info['id'],
                    'openid' => $userinfo['openid'],
                    'openname' => isset($userinfo['userinfo']['nickname']) ? $userinfo['userinfo']['nickname'] : '',
                    'access_token' => $userinfo['access_token'],
                    'refresh_token' => $userinfo['refresh_token'],
                    'expires_in' => $userinfo['expires_in'],
                    'logintime' => time(),
                    'expiretime' => time() + $userinfo['expires_in'],
                ];
                $third = \addons\third\model\Third::create($values);
                $this->success("账号绑定成功");
            }
            if (!$result) {
                $this->error(__($validate->getError()), null, ['token' => $this->request->token()]);
                return false;
            }
            if ($this->auth->login($nickname, $mobile)) {
                //$this->success(__('Logged in successful'), $url ? $url : url('user/index'));
                $this->success(__('Logged in successful'), url('user/index'));
            } else {
                $this->error('姓名或手机号错误', null, ['token' => $this->request->token()]);
            }
        }
        $this->success('正在跳转', '/third/connect/wechat');
        //判断来源
        $referer = $this->request->server('HTTP_REFERER');
        if (!$url && (strtolower(parse_url($referer, PHP_URL_HOST)) == strtolower($this->request->host()))
            && !preg_match("/(user\/login|user\/register|user\/logout)/i", $referer)) {
            $url = $referer;
        }
        $this->view->assign('url', $url);
        $this->view->assign('title', __('Login'));
        return $this->view->fetch();
    }

    /**login
     * 注销登录
     */
    public function logout()
    {
        //注销本站
        $this->auth->logout();
        $this->success(__('Logout successful'), url('user/index'));
    }

    /**
     * 个人信息
     */
    public function profile()
    {
        $this->view->assign('title', __('Profile'));
        return $this->view->fetch();
    }

    /**
     * 修改密码
     */
    public function changepwd()
    {
        if ($this->request->isPost()) {
            $oldpassword = $this->request->post("oldpassword");
            $newpassword = $this->request->post("newpassword");
            $renewpassword = $this->request->post("renewpassword");
            $token = $this->request->post('__token__');
            $rule = [
                'oldpassword' => 'require|length:6,30',
                'newpassword' => 'require|length:6,30',
                'renewpassword' => 'require|length:6,30|confirm:newpassword',
                '__token__' => 'token',
            ];

            $msg = [
            ];
            $data = [
                'oldpassword' => $oldpassword,
                'newpassword' => $newpassword,
                'renewpassword' => $renewpassword,
                '__token__' => $token,
            ];
            $field = [
                'oldpassword' => __('Old password'),
                'newpassword' => __('New password'),
                'renewpassword' => __('Renew password')
            ];
            $validate = new Validate($rule, $msg, $field);
            $result = $validate->check($data);
            if (!$result) {
                $this->error(__($validate->getError()), null, ['token' => $this->request->token()]);
                return false;
            }

            $ret = $this->auth->changepwd($newpassword, $oldpassword);
            if ($ret) {
                $this->success(__('Reset password successful'), url('user/login'));
            } else {
                $this->error($this->auth->getError(), null, ['token' => $this->request->token()]);
            }
        }
        $this->view->assign('title', __('Change password'));
        return $this->view->fetch();
    }

    public function curriculum()
    {
        return $this->view->fetch();
    }

    public function scorelog()
    {
        $list = db('school_user_log')
            ->where('user_id', $this->auth->id)
            ->order('create_time', 'desc')
            ->paginate(10);
        foreach ($list as $k => $v) {
            $v['create_time'] = date('Y-m-d H:i', $v['create_time']);
            $list[$k] = $v;
        }
        $this->assign('list', $list);
        return $this->view->fetch();
    }

    /**
     * 课时卷
     */
    public function juan()
    {
        $list = db('school_coupon')
            ->where('user_id', $this->auth->id)
            ->order('create_time', 'desc')
            ->paginate(10);
        foreach ($list as $k => $v) {
            if ($v['status'] == 0) {
                $v['status_text1'] = '已激活';
            } elseif ($v['status'] == 1) {
                $v['status_text1'] = '进行中';
            }
            //$v['create_time'] = date('Y-m-d H:i', $v['create_time']);
            $list[$k] = $v;
        }
        $this->assign('list', $list);
        return $this->view->fetch();
    }
}
